package com.monitorRoutine.monitorRoutineController.util;

import org.springframework.http.HttpStatus;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public  class DownloadUtil {
    public static String downloadFile(String downloadPath,String savePath) throws IOException {
        // 创建 URL 对象
        URL url = new URL(downloadPath);
        // 下载文件
        try (InputStream in = url.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        }
        return savePath;
    }


    public static void downloadFileWithRetry(String downloadPath, String savePath) throws Exception {
        boolean success = false;
        int count=0;
        while (!success) {
            count=count+1;
            HttpURLConnection conn = (HttpURLConnection) new URL(downloadPath).openConnection();
            conn.setRequestMethod("GET");
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 成功下载文件
                try (InputStream in = conn.getInputStream();
                     FileOutputStream out = new FileOutputStream(savePath)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = in.read(buffer)) > 0) {
                        out.write(buffer, 0, length);
                    }
                }
                success = true;
            } else if (responseCode ==HttpStatus.TOO_MANY_REQUESTS.value()) {
                // 如果请求过多，等待 RETRY_DELAY_MINUTES 秒
                TimeUnit.SECONDS.toMillis(5);
            } else {
                throw new IOException("HTTP Error: " + responseCode);
            }
            conn.disconnect();
            if (count>10){
                throw new Exception("HTTP Error   time out");
            }
        }
    }
}
